package com.imooc.admin.service.impl;

import com.imooc.admin.mapper.CategoryMapper;
import com.imooc.admin.service.CategoryService;
import com.imooc.api.service.BaseService;
import com.imooc.exception.GraceException;
import com.imooc.grance.result.GraceJsonResult;
import com.imooc.grance.result.ResponseStatusEnum;
import com.imooc.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/21/20:01
 * @Description:
 */
@Service
public class CategoryServiceImpl extends BaseService implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Transactional
    @Override
    public void insertCategory(Category category) {
        int result = categoryMapper.insert(category);
        if (result != 1) {
            GraceException.display(ResponseStatusEnum.INSERT_FAILED);
        }
        //添加分类之后删除redis中key，这样前端再次访问的时候就会重新从数据库中查询，已获得最近的分类列表
        redis.del(REDIS_ALL_CATEGORY);
    }

    @Transactional
    @Override
    public void updateCategory(Category category) {
        Example example = new Example(Category.class);
        Example.Criteria crit = example.createCriteria();
        crit.andEqualTo("id", category.getId());
        crit.andEqualTo("name", category.getName());
        int result = categoryMapper.updateByExampleSelective(category, example);
        if (result != 1) {
            GraceException.display(ResponseStatusEnum.UPDATE_CATEGORY_FAILED);
        }
        //修改之后删除redis中key，这样前端再次访问的时候就会重新从数据库中查询，已获得最近的分类列表
        redis.del(REDIS_ALL_CATEGORY);
    }

    /**
     * 判断分类是否已经存在,存在返回false，不存在返回true
     * @param name
     * @return
     */

    @Override
    public boolean queryIsExist(String name) {
        Example example = new Example(Category.class);
        Example.Criteria criteria =example.createCriteria();
        criteria.andEqualTo("name", name);
        Category category = categoryMapper.selectOneByExample(example);
        if (category != null) {
            return false;
        }
        return true;
    }
    @Override
    public List<Category> findAll() {
        List<Category> categories = categoryMapper.selectAll();
        return categories;
    }
    @Override
    public List<Category> findAllCats() {
        List<Category> categories = categoryMapper.selectAll();
        return categories;
    }
}
